<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\HomeBaseController;
use app\portal\model\PortalCategoryModel;
use app\portal\service\PostService;
use app\portal\model\PortalPostModel;
use app\admin\model\class_blogModel;
use think\Db;

class ArticleController extends HomeBaseController
{
    public function index()
    {

        $portalCategoryModel = new PortalCategoryModel();
        $postService         = new PostService();

        $articleId  = $this->request->param('id', 0, 'intval');
        $categoryId = $this->request->param('cid', 0, 'intval');
        $article    = $postService->publishedArticle($articleId, $categoryId);

        if (empty($article)) {
            abort(404, '文章不存在!');
        }


        $prevArticle = $postService->publishedPrevArticle($articleId, $categoryId);
        $nextArticle = $postService->publishedNextArticle($articleId, $categoryId);

        $tplName = 'article';

        if (empty($categoryId)) {
            $categories = $article['categories'];

            if (count($categories) > 0) {
                $this->assign('category', $categories[0]);
            } else {
                abort(404, '文章未指定分类!');
            }

        } else {
            $category = $portalCategoryModel->where('id', $categoryId)->where('status', 1)->find();

            if (empty($category)) {
                abort(404, '文章不存在!');
            }

            $this->assign('category', $category);

            $tplName = empty($category["one_tpl"]) ? $tplName : $category["one_tpl"];
        }

        Db::name('portal_post')->where(['id' => $articleId])->setInc('post_hits');


        hook('portal_before_assign_article', $article);

        $this->assign('article', $article);
        $this->assign('prev_article', $prevArticle);
        $this->assign('next_article', $nextArticle);

        $tplName = empty($article['more']['template']) ? $tplName : $article['more']['template'];

        return $this->fetch("/$tplName");
    }

    // 文章点赞
    public function doLike()
    {
        $this->checkUserLogin();
        $articleId = $this->request->param('id', 0, 'intval');


        $canLike = cmf_check_user_action("posts$articleId", 1);

        if ($canLike) {
            Db::name('portal_post')->where(['id' => $articleId])->setInc('post_like');

            $this->success("赞好啦！");
        } else {
            $this->error("您已赞过啦！");
        }
    }
	
	// 个人简介文章
	public function introduction_article(){
		if($this->request->param()){
			$param = $this->request->param();
			$result = db('teacher')->where('id='.$param['id'])->find();
			$result['introduction'] = cmf_replace_content_file_url(htmlspecialchars_decode($result['introduction']));
			$this->assign("article", $result);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	// 校区详情页
	public function campus(){
		if($this->request->param()){
			$param = $this->request->param();
			$result = db('campus')->where('id='.$param['id'])->find();
			$point = json_decode($result['location'],true);
			$result['lng'] = $point['lng'];
			$result['lat'] = $point['lat'];
			$this->assign("param", $result);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	// 班级资料页
	public function blog(){
		if($this->request->param()){
			$param = $this->request->param();
			$page = isset($param['page'])?$param['page']:1;
			if(!isset($param['timetable_id'])){
				if(!isset($param['class_id'])){
					$this->error('非法访问！');
				}
				else{
					$class_id = $param['class_id'];
					$class = db('class')->where(['id'=>$param['class_id']])->find();
					$this_timetable_data = db('class_timetable')->where(['class_id'=>$param['class_id']])->find();
					$this_timetable_data['times'] = 0;
					$this_timetable_data['class_name'] = $class['name'];

					$class_timetable_list = db('class_timetable')->where(['class_id'=>$param['class_id']])->select();
					// 班级blog数据集
					$blog = new class_blogModel();
					$where = [
						'a.class_id'=>$param['class_id'],
					];
					
					$join = [
						['user u','u.id = a.user_id'],
					];
					if(isset($param['tags'])){
						array_push($join,['blog_tag_post tag','a.id = tag.blog_id AND tag.tag_id ='.$param['tags']]);
					}
					
					$blog_data = $blog
					->alias('a')
					->where($where)
					->where(time().'>publish_time')
					->where(time().'<delete_time')
					->join($join)
					->field('u.user_nickname as user_nickname,title,update_time,content,is_top,post_hits,a.id as id,avatar,is_top,a.more as more')
					->limit(5)
					->page($page)
					->order('is_top desc,update_time desc')
					->select()->toArray();
				}
			}
			else{
				// 当次课表信息
				$this_timetable_data = db('class_timetable')
				->alias('a')
				->where(['a.id'=>$param['timetable_id']])
				->join('class b','b.id = a.class_id')
				->join('classroom c','c.id = a.classroom_id')
				->join('teacher t','t.id = a.teacher_id')
				->field('a.id as id,a.class_id as class_id,a.class_number as class_number,a.times as times,a.start_time as start_time,a.end_time as end_time,b.name as class_name,c.name as classroom_name,t.name as teacher_name')
				->find();
				// 班级课表数据列表
				$class_timetable_list = db('class_timetable')->where(['class_id'=>$this_timetable_data['class_id']])->select();
				$class_id = $this_timetable_data['class_id'];
				// 班级blog数据集
				$blog = new class_blogModel();
				$where = [
					'a.class_id'=>$this_timetable_data['class_id'],
					'a.timetable_id'=>$param['timetable_id'],
				];
				
				$join = [
					['user u','u.id = a.user_id'],
				];
				if(isset($param['tags'])){
					array_push($join,['blog_tag_post tag','a.id = tag.blog_id AND tag.tag_id ='.$param['tags']]);
				}
				
				$blog_data = $blog
				->alias('a')
				->where($where)
				->where(time().'>publish_time')
				->where(time().'<delete_time')
				->join($join)
				->field('u.user_nickname as user_nickname,title,update_time,content,is_top,post_hits,a.id as id,avatar,is_top,a.more as more')
				->limit(5)
				->page($page)
				->order('is_top desc,update_time desc')
				->select()->toArray();
			}
			// 浏览量自增
			foreach($blog_data as $hits_inc){
				$blog->where(['id'=>$hits_inc['id']])->setInc('post_hits',1);
			}
			// 标签数据
			$tags_data = db('blog_tag')->where(['class_id'=>$class_id])->select();
			// 输出内容
			if($this->request->isAjax()){
				foreach($blog_data as &$blog_data_vo){
					$blog_data_vo['update_time'] = date('Y-m-d H:i:s',$blog_data_vo['update_time']);
					$blog_data_vo['post_hits'] += 1;
				}
				$ajaxReturn['data'] = $blog_data;
				$ajaxReturn['page'] = $page;
				return json($ajaxReturn);
			}
			else{
				// dump($blog_data);
				$this->assign('tags_data',$tags_data);
				$this->assign('param',$param);
				$this->assign('blog_data',$blog_data);
				$this->assign('this_timetable_data',$this_timetable_data);
				$this->assign('class_timetable_list',$class_timetable_list);
				return $this->fetch();
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
}
